package thread.concurrents.aqs;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockDemo extends Thread {

  private ReentrantLock reentrantLock = null;

  public Click click;

  public ReentrantLockDemo(ReentrantLock reentrantLock, Click click) {
    this.reentrantLock = reentrantLock;
    this.click = click;
  }

  /**
   * 原子性、可见性
   */
  @Override
  public void run() {
    try {
      this.reentrantLock.lock();
      System.out.println(Thread.currentThread().getName());
      click.a++;
    } finally {
      this.reentrantLock.unlock();
    }
  }

//  @Override
//  public void run() {
//    try {
//      Thread.sleep(100);
//    } catch (InterruptedException e) {
//      e.printStackTrace();
//    }
//      click.a++;
//  }

  static class Click {
    //        volatile int a = 0;
    int a = 0;
  }

  public static void main(String[] args) {

    ReentrantLock reentrantLock = new ReentrantLock(true);
//    ReentrantLockDemo

    Click click = new Click();

    List<ReentrantLockDemo> threads = new LinkedList<>();
    for (int i = 0; i < 5; i++) {
      ReentrantLockDemo retreenLockDemo = new ReentrantLockDemo(reentrantLock, click);
      retreenLockDemo.setName("thread  = " + i);
      threads.add(retreenLockDemo);
    }

    for (ReentrantLockDemo thread : threads) {
      thread.start();
    }

    for (ReentrantLockDemo thread : threads) {
      try {
        thread.join();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }

    System.out.println("结果：" + click.a);

  }

}
